package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.astrob.activitys.AppContext;
import com.astrob.model.Msg;
import com.astrob.nhcmap.R;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.dbmodel.Route;
import com.nhc.database.manager.DBDataCenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.AlertDialog.OnDialogButtonClickListener;
import zuo.biao.library.ui.PageScroller;
import zuo.biao.library.ui.TopMenuWindow;

/**
 * 使用方法：复制>粘贴>改名>改代码
 */

/**
 * activity示例
 *
 * @warn 复制到其它工程内使用时务必修改import R文件路径为所在应用包名
 * @use toActivity(DemoActivity.createIntent(...));
 */
public class NaviLineActivity extends BaseActivity implements OnDialogButtonClickListener {
    private final String TAG = "NaviLineActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    static final String INTENT_FORADDTOLINE = "INTENT_FORADDTOLINE";//点选航线后返回航线的id

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, NaviLineActivity.class);
    }

    public static Intent createIntent(Context context, boolean forAddtoline) {
        return new Intent(context, NaviLineActivity.class)
                .putExtra(INTENT_FORADDTOLINE, forAddtoline);
    }
    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public Activity getActivity() {
        return this;
    }

    boolean _forAddtoline = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //TODO demo_activity改为你所需要的layout文件；传this是为了底部左右滑动手势
        setContentView(R.layout.naviline_activity);

        intent = getIntent();
        _forAddtoline = intent.getBooleanExtra(INTENT_FORADDTOLINE, _forAddtoline);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private ListView lvNaviline;
    private Button bt_do;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE
        lvNaviline = (ListView) findViewById(R.id.lvNaviline);
        bt_do = (Button) findViewById(R.id.bt_do);

    }

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lvNaviline.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> navilinelist;
    private ArrayList<Route> mNaviLineList = new ArrayList<Route>();

    private boolean mIsEdit = false;//选择删除
    private HashMap<Integer, Boolean> hashMap;

    private boolean getItemChecked(int position) {
        return hashMap.get(position);
    }

    private void setItemChecked(int position, boolean isChecked) {
        if (adapter != null) {
            hashMap.put(position, isChecked);
            adapter.notifyDataSetChanged();
        }
    }

    //示例代码>>>>>>>>>
    private void resetRoute() {
        mNaviLineList = DBDataCenter.getInstance().getRouteList();
    }

    @Override
    public void initData() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                resetRoute();
                navilinelist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(navilinelist);
                    }
                });
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    private int avilineNum = 0;

    protected List<Entry<Integer, String>> getList() {
        navilinelist = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < mNaviLineList.size(); i++) {
            navilinelist.add(new Entry<Integer, String>(i, ""));
        }
        avilineNum = navilinelist.size();
        return navilinelist;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<
        lvNaviline.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                setResult(RESULT_OK, new Intent().putExtra(RESULT_CLICKED_ITEM, position));
//                finish();
                if (mIsEdit && null != hashMap) {
                    boolean isSelected = hashMap.get(position);
                    hashMap.put(position, !isSelected);
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                    boolean haveselected = false;
                    for (int i = 0; i < mNaviLineList.size(); i++) {
                        if (hashMap.get(i)) {
                            haveselected = true;
                            break;
                        }
                    }
                    if (haveselected) {
                        bt_do.setText(getString(R.string.delete));
                    } else {
                        bt_do.setText(getString(R.string.cancel));
                    }
                } else {
                    selecteRoute(position);
                }
            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lvNaviline).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>

        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    public static final String RESULT_VALUE = "RESULT_VALUE";

    private void selecteRoute(int index) {
        if (index < 0 || index >= mNaviLineList.size()) {
            return;
        }

        if (_forAddtoline) {
            intent = new Intent();
            intent.putExtra(RESULT_VALUE, mNaviLineList.get(index).getId()+"");
            setResult(RESULT_OK, intent);
            exitAnim = zuo.biao.library.R.anim.left_push_out;
            finish();
        } else {
            DBDataCenter.getInstance().routeEdit = mNaviLineList.get(index);
            toActivity(NaviLineDetailActivity.createIntent(this), REQUEST_TO_ROUTEDETAIL);
        }

    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //@user 新增方法
    @Override
    public void onForwardClick(View v) {
        //top栏右边按钮响应

        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_naviline)), REQUEST_TO_TOP_MENU, false);
    }

    public void onSelectAll(View v) {
        selectAll(true);
    }

    public void onSelectAllNO(View v) {
        selectAll(false);
    }

    public void selectAll(boolean isSelected) {
        if (hashMap == null) {
            hashMap = new HashMap<Integer, Boolean>();
        }
        hashMap.clear();
        if (navilinelist != null) {
            for (int i = 0; i < navilinelist.size(); i++) {
                hashMap.put(i, isSelected);
            }
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

        if (isSelected) {
            bt_do.setText(getString(R.string.delete));
        } else {
            bt_do.setText(getString(R.string.cancel));
        }
    }

    public void onDelSelected(View v) {

        boolean haveselected = false;
        for (int i = 0; i < mNaviLineList.size(); i++) {
            if (hashMap.get(i)) {
                haveselected = true;
                break;
            }
        }

        if (haveselected) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdxzscdhx), true, 0, this).show();
        } else {
            mIsEdit = false;
            findViewById(R.id.ctrl_naviline_edit).setVisibility(View.GONE);
            findViewById(R.id.ctrl_naviline_add).setVisibility(View.VISIBLE);

            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }

    }

    private void delSelected() {
        mIsEdit = false;
        findViewById(R.id.ctrl_naviline_edit).setVisibility(View.GONE);
        findViewById(R.id.ctrl_naviline_add).setVisibility(View.VISIBLE);
        showShortToast(getString(R.string.deleteok));

        ArrayList<Long> pkIds = new ArrayList<Long>();

        for (int i = 0; i < mNaviLineList.size(); i++) {
            if (hashMap.get(i)) {
                pkIds.add(mNaviLineList.get(i).getId());
            }
        }
        DBDataCenter.getInstance().doDeleteRoute(pkIds);

        initData();
    }

    private void clearListData() {
        DBDataCenter.getInstance().doDeleteAllRoute();
        initData();
    }

    private void onToEdit() {
        if (navilinelist.size() < 1) {
            showShortToast(getString(R.string.tnotrackdelete));
            return;
        }

        mIsEdit = true;
        findViewById(R.id.ctrl_naviline_edit).setVisibility(View.VISIBLE);
        findViewById(R.id.ctrl_naviline_add).setVisibility(View.GONE);

        selectAll(false);
    }

    @Override
    public void finish() {
        super.finish();
    }

    public void onAddNaviline(View v) {
        DBDataCenter.getInstance().addNewRoute();
        initData();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                break;
            case KeyEvent.KEYCODE_MENU:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private final int REQUEST_TO_TOP_MENU = 30;
    private final int REQUEST_TO_ROUTEDETAIL = 31;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_TO_ROUTEDETAIL) {
            if (resultCode == Msg.NAVI_BY_ROUTE) {
                setResult(Msg.NAVI_BY_ROUTE);
                finish();
            } else if (resultCode == Msg.NAVI_TO_DEST) {
                setResult(resultCode);
                finish();
            } else {
                initData();
            }
            return;
        }

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            onToEdit();
                            break;
                        case 1:
                            if (navilinelist.size() > 0) {
                                new AlertDialog(context, getString(R.string.wxts), getString(R.string.qclearnaviline), true, 1, this).show();
                            } else {
                                showShortToast(getString(R.string.swjl));
                            }
                            break;
                        default:
                            break;
                    }
                }
                break;
        }
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 0) {
            delSelected();
        } else if (requestCode == 1) {
            clearListData();
        }

    }


    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Adapter
    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.naviline_view, parent, false);
            }

            TextView tvNavilinename = BaseViewHolder.get(convertView, R.id.tvNavilinename);
            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            iv_check.setTypeface(AppContext.getInstances().getIconfont());
            ImageView ivrtimg = BaseViewHolder.get(convertView, R.id.ivrtimg);

            final Entry<Integer, String> data = getItem(position);
            int index = data.getKey();
            if (index >= 0 && index < mNaviLineList.size()) {
                Route naviline = mNaviLineList.get(index);
                tvNavilinename.setText(naviline.getName());

                iv_check.setVisibility(View.GONE);
                if (mIsEdit) {
                    ivrtimg.setVisibility(View.GONE);
                    boolean isSelected = hashMap.get(index);
                    iv_check.setVisibility(View.VISIBLE);
                    if (isSelected) {
                        iv_check.setText(R.string.fonticon_xz);
                    } else {
                        iv_check.setText(R.string.fonticon_wxz);
                    }
                } else {
                    ivrtimg.setVisibility(View.VISIBLE);
                }
            }

            return super.getView(position, convertView, parent);
        }

        private final long serialVersionUID = 3L;

        @Override
        public long getItemId(int position) {
//            return getItem(position).getId();
            return serialVersionUID + position;
        }
    }

}